package com.seo.resolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.seo.pojo.ReturnBody;

import lombok.extern.slf4j.Slf4j;

/**
 * 错误信息
 * 
 * @author shibeilei
 * @version 2017.11.30 12:20
 */
@Slf4j
@ControllerAdvice
public class MyExceptionHandel implements HandlerExceptionResolver {

	@Override
	@ExceptionHandler
	public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler,
			Exception ex) {

		String requestType = request.getHeader("X-Requested-With");
		if (!StringUtils.equals(requestType, "XMLHttpRequest")) {

			String returnUrl = "error/505";
			log.info("错误信息页---{}", ex);
			if (ex instanceof DefiniteException) {
				ModelAndView mv = new ModelAndView(returnUrl);
				mv.addObject("message", ex.getMessage());
				return mv;
			} else {
				ModelAndView mv = new ModelAndView(returnUrl);
				mv.addObject("message", "抱歉，您请求的页面没有找到哦！");
				return mv;
			}
		} else {

			json(response, ex);
			return null;
		}

	}

	public void json(HttpServletResponse response, Exception ex) {
		try {
			ObjectMapper om = new ObjectMapper();
			ReturnBody map = ReturnBody.init();
			map.error(ex.getMessage());
			response.setContentType("application/json");
			response.getWriter().print(om.writeValueAsString(map));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
